<template>
  <el-cascader
    v-model="selectedValues"
    :props="cascaderProps"
    :options="cascaderOptions"
    @change="handleChange"
    :placeholder="placeholder"
    :clearable="clearable"
    :filterable="filterable"
    :multiple="multiple"
    :collapse-tags="collapseTags"
  />
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  clearable: {
    type: Boolean,
    default: true
  },
  filterable: {
    type: Boolean,
    default: true
  },
  multiple: {
    type: Boolean,
    default: true
  },
  collapseTags: {
    type: Boolean,
    default: true
  },
  apiConfig: {
    type: Object,
    required: true,
    validator: value => {
      return ['getTopLevel', 'getChildren'].every(key => key in value)
    }
  }
})

const emit = defineEmits(['update:modelValue', 'change', 'error'])
let selectedValues = ref([...props.modelValue])
const cascaderOptions = ref([])
const nodeDataMap = ref(new Map())

const cascaderProps = {
  lazy: true,
  lazyLoad: async (node, resolve) => {
    try {
      const { level, data: parentNode } = node

      if (level === 0) {
        resolve(cascaderOptions.value)
        return
      }

      const children = await loadChildren(parentNode, level)
      resolve(children)
    } catch (error) {
      console.error('加载子节点失败:', error)
      emit('error', '加载子节点失败')
      resolve([])
    }
  },
  multiple: props.multiple,
  checkStrictly: true
}

// 初始化加载第一级数据
onMounted(async () => {
  await loadFirstLevel()
})

// 监听外部传入的 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  selectedValues.value = [...newVal]
})

// 加载第一级数据
async function loadFirstLevel() {
  try {
    const response = await props.apiConfig.getTopLevel()
    cascaderOptions.value = response.data.data.map(item => ({
      value: item.value,
      label: item.label,
      leaf: false,
      children: []
    }))

    cacheNodes(cascaderOptions.value)
  } catch (error) {
    console.error('加载第一级数据失败:', error)
    emit('error', '加载第一级数据失败')
  }
}

// 加载子节点数据
async function loadChildren(parentNode, level) {
  const response = await props.apiConfig.getChildren({
    parentValue: parentNode.value,
    parentLevel: level
  })

  const children = response.data.data.map(item => ({
    value: item.value,
    label: item.label,
    leaf: level === 2,
    parentValue: parentNode.value,
    children: []
  }))

  if (level === 2) {
    children.unshift(createSelectAllNode(parentNode.value))
  }

  console.log('children', children)
  cacheNodes(children)
  return children
}

// 创建全选节点
function createSelectAllNode(parentValue) {
  return {
    value: `selectAll_${parentValue}`,
    label: '全选',
    leaf: true,
    isSelectAll: true,
    parentValue
  }
}

// 缓存节点数据
function cacheNodes(nodes) {
  nodes.forEach(node => {
    nodeDataMap.value.set(node.value, node)
  })
  console.log('nodeDataMap', nodeDataMap)
}

// 处理选择变化
function handleChange(values) {
  const selectAllValue = values.flat().find(v =>
    typeof v === 'string' && v.startsWith('selectAll_')
  )
  console.log("value:",values)
  console.log('selectAllValue', selectAllValue)

  if (selectAllValue) {
    handleSelectAll(selectAllValue, values)
  } else {
    updateSelectedValues(values)
  }
}

// 处理全选逻辑
async function handleSelectAll(selectAllValue, currentValues) {
  const parentValue = selectAllValue.split('_')[1]
  const parentNode = nodeDataMap.value.get(parentValue)
  console.log('parentNode', parentNode)
  console.log('nodeDataMap', nodeDataMap)


  if (!parentNode.children) {
    await loadChildren(parentNode, 2)
    console.log('parentNode.children', parentNode.children)
  }

  // 获取数组value   [['工学', '交通工程', '10081'], ['工学', '交通工程', '10080']]
  const allLeafNodes = parentNode.children
    .filter(child => !child.isSelectAll && child.leaf)
    .map((child) =>{
      let node ={0:parentNode.parentValue,1:child.parentValue,2:child.value}
      return node
    } )

  console.log('allLeafNodes', allLeafNodes)
  // 判断是否已经全选
  const isAlreadyAllSelected = allLeafNodes.every(node =>
    currentValues.includes(node)
  )

  console.log('isAlreadyAllSelected', isAlreadyAllSelected)

  let newValues
  if (isAlreadyAllSelected) {
    // 取消全选
    newValues = currentValues.filter(
      value => !allLeafNodes.includes(value)
    )
  } else {
    // 执行全选
    newValues = allLeafNodes;
  }

  updateSelectedValues(newValues)
}

// 更新选中值并触发事件
function updateSelectedValues(values) {
  selectedValues = values.map(item => {
    return Object.values(item); // 提取对象的值组成数组
  });

  console.log('selectedValues', selectedValues.value)
  emit('update:modelValue', [...values])
  emit('change', [...values])
}

// 暴露给父组件的方法
defineExpose({
  refresh: async () => {
    nodeDataMap.value.clear()
    await loadFirstLevel()
  }
})
</script>

<style>
:deep(.el-cascader-node__label.select-all) {
  color: var(--el-color-primary);
  font-weight: bold;
}
/* 隐藏级联选择器中父节点的复选框 */
li[aria-haspopup='true'] {
  .el-checkbox {
    display: none;
  }
}
</style>
